/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.inspur.edp.web.jitengine.sourcecode;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.inspur.edp.lcm.metadata.api.IMetadataContent;
import com.inspur.edp.lcm.metadata.api.entity.GspMetadata;
import com.inspur.edp.web.common.environment.ExecuteEnvironment;
import com.inspur.edp.web.common.logger.WebLogger;
import com.inspur.edp.web.common.metadata.MetadataGetterParameter;
import com.inspur.edp.web.common.metadata.MetadataTypeEnum;
import com.inspur.edp.web.common.metadata.MetadataUtility;
import com.inspur.edp.web.common.serialize.SerializeUtility;
import com.inspur.edp.web.common.utility.StringUtility;
import com.inspur.edp.web.sourcecode.metadata.entity.SourceCodeMetadataEntity;

import java.util.ArrayList;
import java.util.List;

/**
 * description:
 *
 * @author Noah Guo
 * @date 2021/03/05
 */
public class SourceCodeInFormManager {
    /**
     * 从元数据内容中获取对应的自定义代码引用关系
     *
     * @param formRefList
     * @param strFormMetadataContent
     */
    public static void getSourceCodeWithFormMetadataContent(List<SourceCodeInFormRef> formRefList, String strFormMetadataContent) {
        ObjectMapper mapper = new ObjectMapper();
        JsonNode jsonNode = null;
        try {
            // 获取表单元数据中对自定义web构件的引用
            JsonNode contentNode = mapper.readTree(strFormMetadataContent).get("Contents");

            if (contentNode.textValue() != null) {
                jsonNode = mapper.readTree(contentNode.textValue()).get("module").get("sourceCodeRef");
            } else {
                jsonNode = mapper.readTree(contentNode.toString()).get("module").get("sourceCodeRef");
            }

            if (jsonNode != null) {
                jsonNode.forEach(node -> {
                    SourceCodeInFormRef sourceCodeInFormRef = getSourceCodeInFormRef(node);
                    if (sourceCodeInFormRef != null) {
                        formRefList.add(sourceCodeInFormRef);
                    }
                });
            }
        } catch (JsonProcessingException e) {
            WebLogger.Instance.error(e);
        }
    }

    /**
     * 根据表单引用关系获取对应的自定义web构件
     *
     * @param sourceCodeInFormRefList
     * @return
     */
    public static List<SourceCodeMetadataEntity> getSourceCodeMetadataEntities(List<SourceCodeInFormRef> sourceCodeInFormRefList, boolean isUpdradeTool) {
        List<SourceCodeMetadataEntity> sourceCodeMetadataEntityList = new ArrayList<>();
        if (sourceCodeInFormRefList != null && sourceCodeInFormRefList.size() > 0) {
            sourceCodeInFormRefList.forEach((formRef) -> {
                String formRefSourceCodeMetadataId = formRef.getId();
                SourceCodeMetadataEntity sourceCodeMetadataEntity = getSourceCodeMetadataWithId(formRefSourceCodeMetadataId, isUpdradeTool);
                if (sourceCodeMetadataEntity != null) {
                    sourceCodeMetadataEntityList.add(sourceCodeMetadataEntity);
                }
            });
        }
        return sourceCodeMetadataEntityList;
    }

    /**
     * 根据元数据id获取对应的元数据内容
     *
     * @param sourceCodeMetadataId
     * @return
     */
    public static SourceCodeMetadataEntity getSourceCodeMetadataWithId(String sourceCodeMetadataId, boolean isUpdradeTool) {
        if (!StringUtility.isNullOrEmpty(sourceCodeMetadataId)) {
            GspMetadata gspMetadata = MetadataUtility.getInstance().getMetadataWithEnvironment(() -> {
                MetadataGetterParameter.GetterMetadataInfo getterMetadataInfo = new MetadataGetterParameter.GetterMetadataInfo();
                getterMetadataInfo.setId(sourceCodeMetadataId);
                getterMetadataInfo.setMetadataType(MetadataTypeEnum.SourceCode);
                return getterMetadataInfo;
            }, null, ExecuteEnvironment.Runtime, isUpdradeTool);
            if (gspMetadata != null) {
                IMetadataContent metadataContent = gspMetadata.getContent();
                SourceCodeMetadataEntity metadataEntity = SerializeUtility.getInstance().deserialize(SerializeUtility.getInstance().serialize(metadataContent, false), SourceCodeMetadataEntity.class);
                return metadataEntity;
            } else {
                WebLogger.Instance.info("根据元数据id获取元数据为空,对应元数据id为" + sourceCodeMetadataId, SourceCodeInFormManager.class.getName());
            }
        }

        return null;
    }

    /**
     * 从dom结构中获取表单引用关系
     *
     * @param node
     * @return
     */
    private static SourceCodeInFormRef getSourceCodeInFormRef(JsonNode node) {
        JsonNode jsonNodeId = node.get("id");
        String strSourceCodeMetadataId = jsonNodeId != null ? jsonNodeId.textValue() : "";

        JsonNode jsonNodeCode = node.get("code");
        String strSourceCodeMetadataCode = jsonNodeCode != null ? jsonNodeCode.textValue() : "";

        JsonNode jsonNodeName = node.get("name");
        String strSourceCodeMetadataName = jsonNodeName != null ? jsonNodeName.textValue() : "";

        SourceCodeInFormRef sourceCodeInFormRef = new SourceCodeInFormRef();
        sourceCodeInFormRef.setId(strSourceCodeMetadataId);
        sourceCodeInFormRef.setCode(strSourceCodeMetadataCode);
        sourceCodeInFormRef.setName(strSourceCodeMetadataName);
        // 如果自定义web构件id为空
        if (StringUtility.isNullOrEmpty(strSourceCodeMetadataId)) {
            return null;
        }
        return sourceCodeInFormRef;
    }

}
